package model

import (
	"common/helper"
	"database/sql"
	"fmt"
	g "github.com/doug-martin/goqu/v9"
	"github.com/doug-martin/goqu/v9/exp"
)

type tblPromoWeekBetConfig struct {
	Id          int     `json:"id" db:"id" cbor:"id"`
	FlowAmount  float64 `json:"flow_amount" db:"flow_amount" cbor:"flow_amount"`
	BonusAmount float64 `json:"bonus_amount" db:"bonus_amount" cbor:"bonus_amount"`
	UpdatedAt   int     `json:"updated_at" db:"updated_at" cbor:"updated_at"`
	UpdatedName string  `json:"updated_name" db:"updated_name" cbor:"updated_name"`
}

type PromoWeekBetData struct {
	BonusAmount float64                 `json:"bonus_amount"`
	ConfigList  []tblPromoWeekBetConfig `json:"config_list"`
}

func PromoWeeklyConfigList(uid string) (PromoWeekBetData, error) {

	var data PromoWeekBetData
	query, _, _ := dialect.From("tbl_promo_weekbet_config").
		Select(colsPromoWeeklyConfig...).Order(g.C("id").Asc()).ToSQL()
	err := meta.SlaveDB.Select(&data.ConfigList, query)
	if err != nil && err != sql.ErrNoRows {
		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), helper.DBErr)
	}

	var validAmount sql.NullFloat64
	ex := g.Ex{"uid": uid, "flag": 1}
	ex["bet_time"] = g.Op{"between": exp.NewRangeVal(helper.WeekTST(0, loc).UnixMilli(), helper.WeekTET(0, loc).UnixMilli())}

	query, _, _ = dialect.From("tbl_game_record").Select(g.SUM("valid_bet_amount").As("valid_bet_amount")).Where(ex).Limit(1).ToSQL()
	err = meta.SlaveDB.Get(&validAmount, query)
	if err != nil {
		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), helper.DBErr)
	}

	data.BonusAmount = validAmount.Float64

	return data, nil
}
